import React, {useState} from 'react';
import {Cascader, Form, Input, message, Modal, Select} from 'antd';
import {http} from 'libs';
import store from '../store';

export default function IForm() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  function handleSubmit() {
    setLoading(true);
    const formData = form.getFieldsValue();
    formData['id'] = store.category.id;
    formData['parent_id'] = formData['parent_id']?.pop()
    http.post('/api/product/category/', formData)
      .then(() => {
        message.success('操作成功');
        store.set('categoryVisible', false);
        store.fetchCategories()
      })
      .finally(() => setLoading(false))
  }

  //id=1,sn=bh,name=打火机,spec=10,unit=盒,price=20.5
  return (
    <Modal
      open
      maskClosable={false}
      title={store.record.id ? '编辑商品分类' : '添加商品分类'}
      onCancel={store.vSet('categoryVisible', false)}
      confirmLoading={loading}
      onOk={handleSubmit}>
      <Form autoComplete='off' form={form} initialValues={store.category} labelCol={{span: 6}} wrapperCol={{span: 14}}>
        <Form.Item required name="name" label="分类名称">
          <Input placeholder="请输入"/>
        </Form.Item>
        <Form.Item required name="sn" label="分类编号">
          <Input placeholder="请输入"/>
        </Form.Item>
        <Form.Item name="parent_id" label="上级分类">
          <Cascader allowClear={false}
                    options={store.categories}
                    fieldNames={{label: 'name', value: 'id'}}
                    placeholder="请输入"/>
        </Form.Item>
      </Form>
    </Modal>
  )
}